package com.test.chatdemo.controller;

import com.test.chatdemo.pojo.Result;
import com.test.chatdemo.utils.CaptchaUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.http.MediaType;
import org.springframework.web.bind.annotation.*;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class CaptchaController {

    private static final Logger log = LoggerFactory.getLogger(CaptchaController.class);

    @Autowired
    private StringRedisTemplate stringRedisTemplate;

    /**
     * 生成验证码（返回Base64图片和验证码文本）
     */
    @GetMapping("/captcha")
    public Result generateCaptcha() {
        try {
            // 生成4位随机验证码
            String captcha = CaptchaUtil.generateRandomCode(4);

            // 生成验证码图片的Base64字符串
            String captchaImage = CaptchaUtil.generateCaptchaImage(captcha);

            // 存储验证码到Redis，使用验证码文本作为标识
            // 这里我们使用 "captcha_code:{验证码}" 作为key
            String redisKey = "captcha_code:" + captcha.toLowerCase();
            stringRedisTemplate.opsForValue().set(redisKey, "valid", 2, TimeUnit.MINUTES);

            log.info("验证码生成成功，code: {}", captcha);

            // 返回验证码图片
            Map<String, String> result = new HashMap<>();
            result.put("captchaImage", captchaImage);
            // 开发环境可以返回验证码文本用于测试
            result.put("captchaText", captcha);

            return Result.success(result);

        } catch (Exception e) {
            log.error("生成验证码失败", e);
            return Result.error("系统繁忙，请稍后重试");
        }
    }

    /**
     * 生成验证码图片流
     */
    @GetMapping(value = "/captcha/image", produces = MediaType.IMAGE_JPEG_VALUE)
    public byte[] generateCaptchaImage() throws IOException {
        try {
            // 生成4位随机验证码
            String captcha = CaptchaUtil.generateRandomCode(4);

            // 存储验证码到Redis
            String redisKey = "captcha_code:" + captcha.toLowerCase();
            stringRedisTemplate.opsForValue().set(redisKey, "valid", 2, TimeUnit.MINUTES);

            log.info("验证码图片生成成功，code: {}", captcha);

            // 生成验证码图片
            BufferedImage image = generateImage(captcha);

            // 转换为字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(image, "JPEG", baos);

            return baos.toByteArray();

        } catch (Exception e) {
            log.error("生成验证码图片失败", e);
            // 返回一个错误图片
            BufferedImage errorImage = new BufferedImage(120, 40, BufferedImage.TYPE_INT_RGB);
            java.awt.Graphics2D g = errorImage.createGraphics();
            g.setColor(java.awt.Color.WHITE);
            g.fillRect(0, 0, 120, 40);
            g.setColor(java.awt.Color.RED);
            g.drawString("ERROR", 30, 25);
            g.dispose();

            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(errorImage, "JPEG", baos);
            return baos.toByteArray();
        }
    }

    // 图片生成方法
    private BufferedImage generateImage(String code) {
        int width = 120;
        int height = 40;

        BufferedImage image = new BufferedImage(width, height, BufferedImage.TYPE_INT_RGB);
        java.awt.Graphics2D g = image.createGraphics();

        // 设置背景色
        g.setColor(java.awt.Color.WHITE);
        g.fillRect(0, 0, width, height);

        // 设置字体
        g.setFont(new java.awt.Font("Arial", java.awt.Font.BOLD, 24));

        // 绘制验证码字符
        java.util.Random random = new java.util.Random();
        for (int i = 0; i < code.length(); i++) {
            // 随机颜色
            g.setColor(new java.awt.Color(
                    random.nextInt(180),
                    random.nextInt(180),
                    random.nextInt(180)
            ));
            // 绘制字符
            g.drawString(String.valueOf(code.charAt(i)), 20 + i * 20, 28);
        }

        // 绘制干扰线
        for (int i = 0; i < 5; i++) {
            g.setColor(new java.awt.Color(
                    random.nextInt(180),
                    random.nextInt(180),
                    random.nextInt(180)
            ));
            int x1 = random.nextInt(width);
            int y1 = random.nextInt(height);
            int x2 = random.nextInt(width);
            int y2 = random.nextInt(height);
            g.drawLine(x1, y1, x2, y2);
        }

        g.dispose();
        return image;
    }
}